package com.partner.frame.support.util;

import java.io.*;
import javax.imageio.*;
import java.util.regex.*;
import java.awt.*;
import java.awt.image.*;
import javax.servlet.http.*;

public class ImageUtil
{
   public static int scalePicFile(String strSrcFile, String strDestFile, String strPicType, int nMaxWidth, int nMaxHeight)
   {
      
      File fileSrc = null;
      Image srcImage = null, destImage = null;
      int nStatus = 0, nSrcWidth = 0, nSrcHeight = 0, nDestWidth = 0, nDestHeight = 0;
      
      try
      {
         fileSrc = new File(strSrcFile);
         fileSrc.setReadOnly();
         srcImage = ImageIO.read(fileSrc);
         
         // 得到图片的原始大小， 以便按比例压缩。
         nSrcWidth = srcImage.getWidth(null);
         nSrcHeight = srcImage.getHeight(null);
         
         //横图
         if(nSrcWidth >= nSrcHeight)
         {
             //源图片宽度大于指定宽度
            if(nSrcWidth > nMaxWidth)
            {
               nDestWidth = nMaxWidth;
               nDestHeight = (int) Math.round(nSrcHeight * 1.0 * nMaxWidth/ nSrcWidth);
            }
            else
            {
               nDestWidth = nSrcWidth;
               nDestHeight = nSrcHeight;
            }
         }
         else
         {
            //源图片高度大于指定高度
           if(nSrcHeight > nMaxHeight)
           {
              nDestHeight = nMaxHeight;
              nDestWidth = (int) Math.round(nSrcWidth * 1.0 * nMaxHeight/ nSrcHeight);
           }
           else
           {
              nDestWidth = nSrcWidth;
              nDestHeight = nSrcHeight;
           }
         }
            
         //按比例缩放
         destImage = srcImage.getScaledInstance(nDestWidth, nDestHeight, Image.SCALE_SMOOTH);
         
//         //处理宽度之后，高度仍超出，以宽度为准，截取中间
//         if(nDestHeight > nMaxHeight)
//            nDestHeight = nMaxHeight;
         nStatus = savePicFile(destImage, nDestWidth, nDestHeight, strPicType, strDestFile);
      }
      catch(Exception eScale)
      {
         nStatus = -1;
         eScale.printStackTrace();
      }
      
      return nStatus;
   }

   public static int savePicFile(Image imageOut, int nMaxWidth, int nMaxHeight, String strPicType, String strDestFile)
   {
      boolean bFlag = false;
      Graphics graphOut = null;
      BufferedImage bufimgOut = null;
      int nStatus = 0, nWidth = 0, nHeight = 0, nTop = 0, nLeft = 0;

      try
      {
         nWidth = imageOut.getWidth(null);
         nHeight = imageOut.getHeight(null);

         // 首先创建一个BufferedImage变量，因为ImageIO写图片用到了BufferedImage变量。
         bufimgOut = new BufferedImage(nWidth, nHeight, BufferedImage.TYPE_INT_RGB);// TYPE_3BYTE_BGR

         // 再创建一个Graphics变量，用来画出来要保持的图片，及上面传递过来的Image变量
         graphOut = bufimgOut.getGraphics();
         // graphOut = bufimgOut.createGraphics();
         if (graphOut == null)
         {
            System.err.println("ImageUtil::savePicFile - graphOut is null");
         }

//         //截取中间部分
//         if(nWidth > nMaxWidth)
//         {
//            nLeft = (nWidth - nMaxWidth)/2;
//            nWidth = nMaxWidth;
//         }
//         else
//            nLeft = 0;
//         
//         if(nHeight > nMaxHeight)
//         {
//            nTop = (nHeight - nMaxHeight)/2;
//            nHeight = nMaxHeight;
//         }
//         else
//            nTop = 0;
         
         nTop = 0;
         nLeft = 0;
         //bFlag = graphOut.drawImage(imageOut, 0, 0, null);
         bFlag = graphOut.drawImage(imageOut, nLeft, nTop, nWidth, nHeight, null);
         graphOut.dispose();
         // if(bFlag == false)
         // {
         // System.err.println("ImageUtil::savePicFile - drawImage false");
         // }

         // 将BufferedImage变量写入文件中。
         System.out.println("ImageUtil::savePicFile - PicType[" + strPicType + "] DestFile[" +
            strDestFile + "] Width[" + nWidth + "] Height[" + nHeight + "]");
         bFlag = ImageIO.write(bufimgOut, strPicType, new File(strDestFile));
         if (bFlag == false)
         {
            System.err.println("ImageUtil::savePicFile - ImageIO.write false");
         }
      }
      catch (Exception eImageOut)
      {
         nStatus = -1;
         eImageOut.printStackTrace();
      }

      return nStatus;
   }

   //kindeditor内容中的img标签，将base64保存为文件
   public static String filterkindeditorImg(String strContent, String strUploadPath, HttpServletRequest httpRequest)
   {
      File filePath = null;
      boolean bStatus = false;
      byte[] btFiledata = null;
      StringBuffer sbContent = null; 
      Pattern patternTag = null, patternData = null, patternExt = null;
      Matcher matcherTag = null, matcherData = null, matcherExt = null;
      String strImgtagRule = "", strImgdataRule = "", strExtRule = "", strImgtag = "";
      String strImgType = "", strReplacetag = "", strImgData = "", strFileurl = "", 
         strPath = "", strFilename = "", strExtname = "", strFileseq = "", strFile = "";
      
      sbContent = new StringBuffer();
      strExtRule = "data:image/(.+?);base64";
      strImgtagRule = "(<img .*?src=\\\"data:image/.+?;base64,.+?\\\"\\s*?/>)";
      strImgdataRule = "<img .*?src=\\\"(data:image/.+?;base64),(.+?)\\\"\\s*?/>";
      System.out.println("strImgtagRule - " + strImgtagRule);
      System.out.println("strImgdataRule - " + strImgdataRule);
      
      //查找img节点
      patternTag = Pattern.compile(strImgtagRule, Pattern.CASE_INSENSITIVE);
      matcherTag = patternTag.matcher(strContent);
      while(matcherTag.find())
      {
         strImgtag = matcherTag.group(1);
         
         //从节点提取img类型及文件数据
         patternData = Pattern.compile(strImgdataRule, Pattern.CASE_INSENSITIVE);
         matcherData = patternData.matcher(strImgtag);
         if(matcherData.find())
         {
            strImgType = matcherData.group(1);
            strImgData = matcherData.group(2);
            
            //获取文件扩展名
            patternExt = Pattern.compile(strExtRule, Pattern.CASE_INSENSITIVE);
            matcherExt = patternExt.matcher(strImgType);
            if(matcherExt.find())
               strExtname = matcherExt.group(1);
            
//            System.out.println("type - " + strImgType);
//            System.out.println("length - " + strImgData.length());
            
            //解码
            btFiledata = CommonUtil.decodeBase64(strImgData);
            
            //生成文件名
            strFileseq = Long.toString(Long.parseLong(CommonUtil.generateSeq().substring(2)), 16);
            strFilename = strFileseq + "." + strExtname;
            
            //文件保存目录、保存文件名
            strFileurl = httpRequest.getContextPath() + strUploadPath + "/" + strFilename;
            //strPath = httpRequest.getServletContext().getRealPath(strUploadPath);
            strFile = strPath + File.separator + strFilename;
            
            //检查目录
            filePath = new File(strPath);
            if(filePath.exists() == false)
            {
               bStatus = filePath.mkdirs();
               if(bStatus == false)
                  System.err.println("TravelattentionManagerImpl::filterkindeditorImg - mkdirs[" + strPath + "] failed");
            }
            
            //保存文件
            CommonUtil.saveFileData(strFile, btFiledata);
            
            //替换img标签
            strReplacetag = "<img alt=\"\" src=\"" + strFileurl + "\" />";
            matcherTag.appendReplacement(sbContent, strReplacetag);
            
//            System.out.println("file = " + strFile);
//            System.out.println("url = " + strFileurl);
//            System.out.println("tag = " + strReplacetag);
         }
         
         //System.out.println("strImgtag - " + strImgtag);
      }
      matcherTag.appendTail(sbContent);
      //System.out.println("strReplacetag - " + sbContent.toString());
      
      return sbContent.toString();
   }
   
   public static void main(String[] args)
   {
      //ImageUtil.scalePicFile("g:/008.jpg", "g:/008008.jpg", "jpg", 480, 800);
      System.out.println(System.currentTimeMillis());
   }

   // ----------------------------awood 2014-07-13----------------------------

}
